<template>
  <div>
    <headNav title="" :isHome="isHome" :signIn="!isHome" ></headNav>
     <div class="flexHeightCenter" >
       <div class="bigDivCss" >
         <div class="flexCenter divs" >
           <span style="color: red;" >*</span>
           <span>班级号：</span>
         </div>
         <input type="text" v-model="childrenVal.qrCode" placeholder="请输入班级号" v-if="childrenVal.status == undefined"
          @blur="formChange"
          />
         <div v-else class="editData" >{{childrenVal.qrCode}}</div>
         <!-- <div v-show="childrenVal.status == 1" class="xiu-gai">修改</div> -->
       </div>

       <div class="bigDivCss" >
         <div class="flexCenter divs" >
           <span style="color: red;" >*</span>
           <span>姓 名：</span>
         </div>
         <input type="text" v-model="childrenVal.studentName" placeholder="请输入学生姓名" v-if="!editData" 
          @blur="formChange"
         />
         <div v-else class="editData" >{{childrenVal.studentName}}</div>
         <!-- <div v-show="childrenVal.status == 1" class="xiu-gai">修改</div> -->
       </div>

       <div class="bigDivCss" >
         <div class="flexCenter divs" >
           <span>性  别：</span>
         </div>
         <div class="flexAlign tana"  :class="{disabledCss: editData}" >
        

           <gender :disable="editData" v-model="childrenVal.gender" @change="formChange"></gender>
           

         </div>
        
       </div>

       <div class="bigDivCss" >
         <div class="flexCenter divs" >
           <span>入学时间：</span>
         </div>
         <div class="flexAlign tana" :class="{disabledCss: editData}">
            <selectDate :disable="editData" v-model="childrenVal.enrolmentDate" @change="formChange"></selectDate>
            
         </div>
        
        
       </div>

       <div class="bigDivCss" >
         <div class="flexCenter divs" >
           <span>证件类型：</span>
         </div>
         <div class="flexAlign tana" :class="{disabledCss: editData}" >
           <certify :disable="editData" v-model="childrenVal.idTypeCode" @change="formChange"></certify>
           
         </div>
       
       </div>

       <div class="bigDivCss" >
         <div class="flexCenter divs" >
           <span>证件号：</span>
         </div>
         <div v-if="editData" class="editData" >{{childrenVal.idNumber}}</div>
         <input type="text" v-model="childrenVal.idNumber" :placeholder="childrenVal.idTypeCode ? '请输入证件号' : '请先选择证件类型'" 
         v-if="!editData" :disabled="!childrenVal.idTypeCode" :class="{disabledCss:!childrenVal.idTypeCode}" 
          @blur="formChange"
          />

          <!-- <div v-show="childrenVal.status == 1" class="xiu-gai">修改</div> -->
       </div>

       <div class="bigDivCss" >
         <div class="flexCenter divs" >
           <span>亲属关系：</span>
         </div>
         <div class="flexAlign tana"  :class="{disabledCss: editData}" >
           <relation :disable="editData" v-model="childrenVal.relationCode" @change="formChange"></relation>
         </div>
        
       </div>

       <div class="flexAlign headDiv" >
         <div>
           <span>人脸头像：</span>
         </div>
        <img v-if="childrenVal.faceImgUrl" :src="childrenVal.faceImgUrl" @click="preivewImg(childrenVal.faceImgUrl)" alt=""   >
        <img v-else src="@/assets/img/default_heads.png" alt=""  >

         <!-- <img v-if="childrenVal.faceImgUrl && imgDataSource.length == 0 " :src="childrenVal.faceImgUrl" alt=""  @click="uploadImg" >
         <img v-if="!childrenVal.faceImgUrl && imgDataSource.length == 0" src="@/assets/img/default_heads.png" alt=""  @click="uploadImg" >
         <img v-if="imgDataSource.length > 0" :src="imgDataSource[imgDataSource.length - 1]" alt=""  @click="uploadImg" > -->
          <div @click="uploadImg" class="upload-btn">点击上传图片</div>
         <span class="spanSample" @click="showHideOnBlur = true" >样本示例  ></span>
       </div>
     

       <div class="flexCenter buttonCss" >
         <button type="default"  @click="packAddChild" v-if="childrenVal.status === undefined">
            提交审核
         </button>
         <button type="default"  @click="packAddChild" v-if="childrenVal.status == 2">
           重新提交审核
         </button>
         
         <button type="default" style="color: #128FEF; background: #FFF;" v-if="childrenVal.status == 1" @click="deleteClick" >删除关联</button>
     
       </div>
     </div>

     <!-- 样本实例弹窗 -->
     <x-dialog v-model="showHideOnBlur" class="dialog-demo xdialog" hide-on-blur>
      <div class="flexCenter popupCss" >
        <img src="@/assets/img/my/examples.png" alt="" style="width: 100%;" >
      </div>
     </x-dialog>
  </div>
</template>

<script>
import headNav from '@/components/headNav/headNav.vue'
import { mapActions, mapState, mapGetters, mapMutations } from 'vuex'
import { PopupHeader, Popup, Radio, Group, Datetime, XDialog } from 'vux'
import { getDictionariesApi, postChildAuditApi, updateChildAuditApi, getClassNumberApi, deleteChildContactApi, getChildRecordsApi, postTestingAddApi } from '@/api/myNewApi'
import {addFaceResource} from '@/api/faceApi' 
import cookie from '@/util/cookie'
import {refreshToken} from '@/api/commonApi'
import gender from './component/gender'
import certify from './component/certify'
import relation from './component/relation'
import selectDate from './component/selectDate'

export default {
  components: {
    headNav,
    PopupHeader,
    Popup,
    Radio,
    Group,
    Datetime,
    XDialog,
 
    gender,
    certify,
    relation,
    selectDate
  },
  computed: {
    ...mapState({
      studentId: state => state.user.studentId,
      roleCode: state => state.user.roleCode,
      loginUserId: state => state.user.loginUserId,
      schoolId: state => state.user.schoolId,
      imgDataSource () {
        return this.$store.state.media.imgDataSource
      },
    })
  },
  data () {
    return {
      isHome: false,
     
      headImg: '', // 存放人脸头像链接
      showHideOnBlur: false,  // 示例弹窗控制
     
     
      editData: false,  // 控制输入框是否禁用
      childrenVal: '',    // 孩子的信息
    }
  },
  methods: {
    preivewImg(url){
      wx.previewImage({
        current: url, 
        urls: [url] 
      });
    },

    // 删除关联按钮触发事件
    async deleteClick () {
      this.$vux.confirm.show({
          title: '提示',
          content: '是否确定删除关联？',
          onConfirm : async () => {
            let params = {
              id: this.childrenVal.id,
              LoginUserId: this.cookieLoginUserId,
              StudentId: this.childrenVal.studentId
            }

            await deleteChildContactApi(params)
            // JSON.stringify
            localStorage.reloadJudge = true
            this.$vux.toast.text('关联已取消', 'middle')
            this.$router.push('children')
          },
          onCancel () {
          }
      })
    },
    // 上传图片按钮触发事件
    async uploadImg(){
      if (this.editData) {
        return
      } else {
        await this.$store.dispatch('media/getFaceImg')
        
         localStorage.editChildren = JSON.stringify(this.childrenVal)
         this.$router.push('childFace')
 
      }
    },

    formChange() {
      if(this.childrenVal.status == 1) {
          if (!this.checkData()) {
            return
          }
          this.submit()
      }
    },

    async addFaceResource () {
        if (!this.childrenVal.faceImgUrl) {
          return
        }

      

        var person = {
          externalFields: {
            externalFields: {
                    schoolId: this.childrenVal.schoolId,
                    className: '',
                    personId: this.childrenVal.studentId,
                  
                    name: '',
                    faceImgUrl: '',
                    gender: this.childrenVal.gender ? 1 : 0,
                    personType: 1   // 教师：0，学生：1
            }
          },
          faceSetName: this.childrenVal.schoolId,
          personName: this.childrenVal.studentName,
          imageUrl: this.childrenVal.faceImgUrl,
           living: true
        }
        let res = await addFaceResource(person)

        if (res.status != 200) {
          this.$vux.alert.show({
              title: '错误',
              content: res.msg,
          })

          this.childrenVal.faceImgUrl = null

          throw new Error(res.msg);
        } 
    },

    // 确定添加学生按钮触发
    async packAddChild () {
      if (!this.checkData()) {
        return
      }
      
      this.$vux.confirm.show({
          title: '提示',
          content: '是否确定提交？',
          onConfirm : async () => {
           
            this.submit()

          },
          onCancel () {
          }
      })

    },

    checkData(){
        if (!this.childrenVal.studentName || !this.childrenVal.qrCode) {
        this.$vux.toast.text('班级号和姓名不能为空', 'middle')
        return false
      }

      this.childrenVal.studentName = this.childrenVal.studentName.replace(/ /g,'')
      if (this.childrenVal.studentName.length > 8) {
        this.$vux.toast.text('姓名长度过长，限制8个字', 'middle')
        return false
      }

      if (!this.childrenVal.studentName || !this.childrenVal.qrCode) {
        this.$vux.toast.text('班级号和姓名不能为空', 'middle')
        return false
      }


      if (this.childrenVal.idNumber) {
        this.childrenVal.idNumber = this.childrenVal.idNumber.replace(/ /g,'')
      }
      if (this.childrenVal.idNumber && 18 < this.childrenVal.idNumber.length > 0) {
        this.$vux.toast.text('证件码长度过长，限制18个字', 'middle')
        return false
      }

      return true
    },

    async submit(){
        let data = {
              qrcode: this.childrenVal.qrCode
            }
            let val = await getClassNumberApi(data)
           
            let params = JSON.parse(JSON.stringify(this.childrenVal))
            params.loginUserId = this.cookieLoginUserId
            params.schoolClassId = val.id
            
            if (params.enrolmentDate){
              if(params.enrolmentDate.indexOf(' ') == -1) {
                params.enrolmentDate = params.enrolmentDate + ' 00:00:00'
              }
            }
            
           
            if (!val) {
              this.$vux.toast.text('班级号不存在，请确认', 'top')
              return
               
            }
            
            // 新增孩子
            if (this.childrenVal.status == undefined) {
              await postChildAuditApi(params)
              this.$vux.toast.text('提交成功', 'middle')
              this.$router.push('children')
            }

            // 待审核，不做处理
            if (this.childrenVal.status == 0) {
              
            }

            // 已绑定，修改孩子信息
            if (this.childrenVal.status == 1) {
                await this.addFaceResource()

                params.id = this.childrenVal.id
                params.status = 1
                await updateChildAuditApi(params)
                this.$vux.toast.text('修改成功', 'middle')
            }

            // 被驳回，重新提交审核
            if (this.childrenVal.status == 2) {
                params.id = this.childrenVal.id
                params.status = 0
                await updateChildAuditApi(params)

                this.$vux.toast.text('提交成功', 'middle')

                this.$router.push('children')
            }
 
            await this.$store.dispatch('user/refreshAccessToken')
            this.$store.commit('user/setRoleCode', 'Parent')
            localStorage.removeItem('localQRCode')
             localStorage.removeItem('editChildren')
          
            
            // this.$router.push('children')
    }
  },
  async mounted() {
    localStorage.removeItem('role')
    

    this.cookieLoginUserId = cookie.get('loginUserId')

    if (localStorage.editChildren) {

        this.childrenVal = JSON.parse(localStorage.editChildren)
      
        if(this.childrenVal.status == 0) {
          this.editData = true
        } 
     
     
    } else {
        this.childrenVal = {
          qrCode: localStorage.localQRCode
        }
        
    }

    // 当头像改变的时候
    if(this.$store.state.myInfo.childFace){
      this.childrenVal.faceImgUrl = this.$store.state.myInfo.childFace
      this.$store.state.myInfo.childFace = ''

      this.formChange()
    }
    



    let res = await getChildRecordsApi()
    if (res.length == 0) {
      this.isHome = false
     
      return
    } else {
      for (let val of res) {
        if (val.statusDesc == '已绑定') {
          this.isHome = true
         
          return
        } else {
          this.isHome = false
          
        }
      }
    }


  }
}
</script>

<style lang="less" scoped >
.dateCss {
  width: 4rem;
  height: 0.5rem;
  background: #FFF;
  border-radius: 0.2rem;
  margin-top:0.08rem;
  color: #128FEF;
  display: inline-block;
    vertical-align: middle;
   
}

.disabledCss {
  background: #eae7e7!important;
}

 .buttonCss {
   width: 100%;
   margin-top: 0.3rem;
   button {
     background: #128FEF;
     color: #FFF;
     width: 5.6rem;
     height: 0.85rem;
     font-size: 0.32rem;
     border: 1px solid #128FEF;
     border-radius: 0.42rem;
     outline:0;
     margin-bottom: 0.5rem
   }
 }

 .headDiv {
   width: 6.6rem;
   height: 1rem;
   font-size: 0.28rem;
   margin-top: 0.4rem;
   position: relative;
   img {
     width: 0.85rem;
     border-radius: 0.1rem;
     height: 0.85rem;
     object-fit: cover;
   }
  
   .spanSample {
     color: #128FEF;
    position: absolute; right: 0; top: 50%; transform: translateY(-50%);
   }
 }

.bigDivCss {
  position: relative;
  width: 6.6rem;
  height: 1rem;
  font-size: 0.28rem;
 
  margin-top: 0.4rem;
  input {
    background: #ffffff;
    width: 4rem;
    height: 0.85rem;
    padding-left: 0.2rem;
    font-size: 0.28rem;
    border-radius: 0.2rem;
    
    display: inline-block;
    vertical-align: middle;
  }
  .editData {
    width: 4.5rem;
    height: 0.85rem;
    padding-left: 0.2rem;
    font-size: 0.28rem;
    border-radius: 0.2rem;
    line-height: 0.85rem;
    color: #8a8181;
    background: #eae7e7;
        display: inline-block;
    vertical-align: middle;
  }
  .tana {
    background: #ffffff;
    width: 4rem!important;
    height: 0.85rem;
    line-height: 0.85rem;
    padding-left: 0.2rem;
    font-size: 0.28rem;
    border-radius: 0.2rem;
   
    display: inline-block;
    vertical-align: middle;
  }
  .divs {
    width: 1.5rem;
    display: inline-block;
    vertical-align: middle;
  }
}

input::-webkit-input-placeholder {
  color: #8a8181;
}

.flexCenter {
  display: flex;
  align-items: center;
  justify-content: center;
}

.flexHeight {
  display: flex;
  flex-direction: column;
}

.flexHeightCenter {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.flexAlign {
  display: flex;
  align-items: center;
}

.flexEdge {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.xiu-gai{
  color: #128FEF; position: absolute;right: 0; top: 50%; transform: translateY(-50%);
}
.upload-btn{
  color: #128FEF; display: inline-block; vertical-align: middle;
      padding: 0 0 0 0.2rem;
}
</style>
<style>
.dateCss .weui-cell__ft {
  text-align: left!important;
}

.dateCss .vux-cell-placeholder {
  color: #8a8181!important;
}

.dateCss .vux-cell-value {
  color: #8a8181!important;
}

</style>
